package com.yz.xyt.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yz.xyt.constant.Constants;
import com.yz.xyt.constant.HttpStatus;
import com.yz.xyt.domain.Post;
import com.yz.xyt.domain.ResponseResult;
import com.yz.xyt.domain.Staff;
import com.yz.xyt.domain.User;
import com.yz.xyt.domain.vo.StaffImportVo;
import com.yz.xyt.domain.vo.StaffVo;
import com.yz.xyt.mapper.PostMapper;
import com.yz.xyt.mapper.StaffMapper;
import com.yz.xyt.service.IDepartmentService;
import com.yz.xyt.service.IRoleService;
import com.yz.xyt.service.IStaffService;
import com.yz.xyt.service.IUserService;
import com.yz.xyt.utils.DateUtils;
import com.yz.xyt.utils.SecurityUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StaffServiceImpl implements IStaffService {

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;
    @Autowired
    PostMapper postMapper;

    @Autowired
    IDepartmentService departmentService;

    @Override
    public int deleteByPrimaryKey(Integer staffId) {
        return staffMapper.deleteByPrimaryKey(staffId);
    }

    @Override
    public int insert(Staff record) {
        return staffMapper.insert(record);
    }

    @Override
    public int insertSelective(Staff record) {
        return staffMapper.insertSelective(record);
    }

    @Override
    public Staff selectByPrimaryKey(Integer staffId) {
        return staffMapper.selectByPrimaryKey(staffId);
    }

    @Override
    public int updateByPrimaryKeySelective(Staff record) {
        return staffMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Staff record) {
        return staffMapper.updateByPrimaryKey(record);
    }

    @Override
    public int updateByStaffNumberSelective(Staff record) {
        return staffMapper.updateByStaffNumberSelective(record);
    }

    @Override
    public Staff findByStaffNumber(String staffNumber) {
        return staffMapper.findByStaffNumber(staffNumber);
    }

    @Override
    public int deleteByStaffNumber(String staffNumber) {
        return staffMapper.deleteByStaffNumber(staffNumber);
    }

    @Transactional
    @Override
    public void syncAddStaff(List<Staff> lists) {
        List<List<Staff>> partition = ListUtils.partition(lists, 100);
        for (List<Staff> list : partition){
            //过滤重复数据
            List<Staff> staffList = new ArrayList<>();
            list.stream().forEach(staff -> {
                Staff record = findByStaffNumber(staff.getStaffNumber());
                //智慧校园同步接口能使用用是释放此处代码
//                if (record == null && StringUtils.isNotEmpty(staff.getPostNumber())){
//                    staffList.add(staff);
//                }
                //智慧校园同步接口能使用时，注释此段代码
                if (record ==null){
                    staffList.add(staff);
                }
            });
            //新增教职工
            staffList.stream().peek(staff -> {
                staff.setCreateBy(SecurityUtils.getUsername());
                staff.setCreateDate(DateUtils.getNowDate());
            }).collect(Collectors.toList()).stream().forEach(this::insertSelective);

            //创建系统用户
            List<User> accountList = new ArrayList<>();
            createSystemUser(staffList, accountList, false);
            userService.createSystemAccount(accountList);
            //添加用户角色
            userRoleManager(staffList, false);
        }
    }

    @Transactional
    @Override
    public void syncUpdateStaff(List<Staff> lists) {
        List<List<Staff>> partition = ListUtils.partition(lists, 100);
        for (List<Staff> list : partition){
            //角色变动的职工
            List<Staff> roleChanges = new ArrayList<>();
            //角色变动的职工的数据库记录
            List<Staff> records = new ArrayList<>();

            //更新教职工信息
            list.stream().peek(staff -> {
                //数据库记录
                Staff record = staffMapper.findByStaffNumber(staff.getStaffNumber());
                if (StringUtils.isNotEmpty(record.getRoleId()) && !record.getRoleId().equals(staff.getRoleId())){
                    roleChanges.add(staff);
                    records.add(record);
                }
                staff.setUpdateBy(SecurityUtils.getUsername());
                staff.setUpdateDate(DateUtils.getNowDate());
            }).collect(Collectors.toList()).forEach(this::updateByStaffNumberSelective);

            //角色变动的教职工，先删除原有账号和角色再重建
            if (roleChanges.size() > 0){
                syncDeleteStaff(records);
                syncAddStaff(roleChanges);
                //移除角色变动的数据
                list.removeAll(records);
            }

            //其他信息变动的教职工直接更新
            List<User> accountList = new ArrayList<>();
            if (list.size() > 0){
                createSystemUser(list, accountList, true);
                //更新系统账号信息
                accountList.stream().forEach(user -> userService.updateByUserNameSelective(user));
                //添加用户角色
                userRoleManager(list, true);
            }
        }
    }

    @Transactional
    @Override
    public void syncDeleteStaff(List<Staff> lists) {
        List<List<Staff>> partition = ListUtils.partition(lists, 100);
        for (List<Staff> list : partition){
            list.stream().forEach(staff -> {
                staffMapper.deleteByStaffNumber(staff.getStaffNumber());
                List<String> roles = new ArrayList<>();
                if (StringUtils.isNotEmpty(staff.getRoleId())) {
                    roles = Arrays.asList(staff.getRoleId().split(","));
                }
                if (roles.size() > 1){
                    for (String role : roles){
                        String userName = staff.getStaffNumber() + "@" + role;
                        User user = userService.findUser(userName);
                        if (user != null){
                            roleService.deleteUserRole(user.getId());
                            userService.deleteByUserName(userName);
                        }
                    }
                }else{
                    User user = userService.findUser(staff.getStaffNumber());
                    if (user != null){
                        roleService.deleteUserRole(user.getId());
                        userService.deleteByUserName(staff.getStaffNumber());
                    }
                }
            });
        }
    }

    /**
     * 查询教职工列表
     *
     * @param staffVo
     * @return
     */
    @Override
    public PageInfo findStaffForPage(StaffVo staffVo) {
        //分页查询开始
        PageHelper.startPage(staffVo.getPageNumber(), staffVo.getPageSize());
        List<StaffVo> staffList = staffMapper.findStaffList(staffVo);
        return new PageInfo(staffList);
    }

    /**
     * 查询教职工个人信息
     *
     * @param staffNumber
     * @return
     */
    @Override
    public StaffVo findStaffInfo(String staffNumber) {
        if (staffNumber.contains("@")){
            staffNumber = staffNumber.substring(0,staffNumber.indexOf("@"));
        }
        StaffVo staffVo = staffMapper.selectStaffInfo(staffNumber);
        if (null != staffVo && StringUtils.isNotEmpty(staffVo.getPostNumber())) {
            List<String> postNumbers = Arrays.asList(staffVo.getPostNumber().split(","));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < postNumbers.size(); i++) {
                Post post = postMapper.findByPostNumber(postNumbers.get(i));
                if (post != null) {
                    String postName = post.getPname();
                    if (StringUtils.isNotEmpty(postName)) {
                        if (i > 0) {
                            builder.append("," + postName);
                        } else {
                            builder.append(postName);
                        }
                    }
                }
            }
            staffVo.setPostName(builder.toString());
        }
        return staffVo;
    }

    /**
     * 用户角色管理
     *
     * @param list
     * @param isUpdate
     */
    private void userRoleManager(List<Staff> list, boolean isUpdate) {
        list.forEach(staff -> {
            //获取角色Id
            List<String> roles = new ArrayList<>();
            if (StringUtils.isNotEmpty(staff.getRoleId())) {
                roles = Arrays.asList(staff.getRoleId().split(","));
            }

            if (isUpdate) {
                if (roles.size() > 1){
                    roles.stream().forEach(s -> {
                        User user = userService.findUser(staff.getStaffNumber() + "@" + s);
                        //删除原有角色
                        roleService.deleteUserRole(user.getId());
                    });
                }else{
                    User user = userService.findUser(staff.getStaffNumber());
                    //删除原有角色
                    roleService.deleteUserRole(user.getId());
                }
            }
            if (roles.size() > 1){
                roles.stream().forEach(s -> {
                    User user = userService.findUser(staff.getStaffNumber() + "@" + s);
                    //添加用户角色
                    roleService.addUserRole(user.getId(), Long.valueOf(s));
                });
            }else{
                roles.stream().forEach(s -> {
                    User user = userService.findUser(staff.getStaffNumber());
                    //添加用户角色
                    roleService.addUserRole(user.getId(), Long.valueOf(s));
                });
            }
        });
    }

    /**
     * 创建系统用户
     *
     * @param list
     * @param accounts
     * @param isUpdate
     * @return
     */
    private void createSystemUser(List<Staff> list, List<User> accounts, boolean isUpdate) {

        list.stream().forEach(staff -> {
            User user = new User();
            //更新信息时，不更新原有密码
            if (!isUpdate) {
//                if (StringUtils.isNotEmpty(staff.getPhone())) {
////                    String phone = staff.getPhone();
////                    //验证是否是手机号
////                    boolean isPhone = RegexUtils.checkMobile(phone);
////                    if (!isPhone) {
////                        user.setPassword(Constants.DEFAULT_PASSWORD);
////                    } else {
////                        user.setPassword(staff.getPhone().substring(staff.getPhone().length() - 6));
////                    }
////                } else {
////                    user.setPassword(Constants.DEFAULT_PASSWORD);
////                }
                user.setPassword(Constants.DEFAULT_PASSWORD);
                user.setCreateBy(staff.getUpdateBy());
                user.setCreateDate(staff.getUpdateDate());
            } else {
                user.setCreateBy(staff.getCreateBy());
                user.setCreateDate(staff.getCreateDate());
            }
            user.setPhone(staff.getPhone());
            user.setAccountName(staff.getName());
            user.setSex(staff.getSex());
            //01	退休
            //02	离休
            //03	死亡
            //04	返聘
            //05	调出
            //06	辞职
            //07	离职
            //08	开除
            //09	下落不明
            //11	在职
            //12	延聘
            //13	待退休
            //14	长病假
            //15	因公出国
            //16	停职留薪
            //17	待岗
            //99	其他
            //18	因私出国
            //19	内退
            //21	挂职
            //20	自主创业
            //22	在岗
            if (staff.getStatus().equals("11") || staff.getStatus().equals("22")) {
                user.setStatus(Constants.ACCOUNT_ENABLE);
            } else {
                user.setStatus(Constants.ACCOUNT_DISABLE);
            }
            //多重角色添加多个账号
            List<String> roles = new ArrayList<>();
            if (StringUtils.isNotEmpty(staff.getRoleId())) {
                roles = Arrays.asList(staff.getRoleId().split(","));
            }
            if (roles.size() > 1) {
                for (String role : roles) {
                    User tmp = new User();
                    tmp.setUserName(staff.getStaffNumber() + "@" + role);
                    tmp.setPassword(user.getPassword());
                    tmp.setStatus(user.getStatus());
                    tmp.setAccountName(user.getAccountName());
                    tmp.setSex(user.getSex());
                    tmp.setPhone(user.getPhone());
                    tmp.setCreateBy(user.getCreateBy());
                    tmp.setCreateDate(user.getCreateDate());
                    accounts.add(tmp);
                }
            } else {
                user.setUserName(staff.getStaffNumber());
                accounts.add(user);
            }
        });
    }

    /**
     * 查询教师工号
     * @param staffName
     * @return
     */
    @Override
    public String findStaffNumberByName(String staffName) {
        return staffMapper.findStaffNumberByName(staffName);
    }

    @Override
    public List<Staff> convertStaff(List<StaffImportVo> staffList) {
        List<Staff> list = new ArrayList<>();
        staffList.stream().forEach(s ->{
            //获取部门编号
            String deptNumber = departmentService.findDeptNumberByName(s.getDeptName());
            //查询角色ID
            String roleName =  s.getRoleName();
            if(StringUtils.isNotEmpty(roleName)){
                if (roleName.contains("领导")){
                    roleName = "分管领导";
                }
                if (roleName.contains("处长")){
                    roleName = "学生处";
                }
                if (roleName.contains("书记")){
                    roleName = "书记";
                }
                String roleId = roleService.findRoleIdByName(roleName);
                if (StringUtils.isNotEmpty(deptNumber) && StringUtils.isNotEmpty(roleId)){
                    Staff staff = new Staff();
                    staff.setRoleId(roleId);
                    staff.setSex(s.getSex());
                    staff.setDeptNumber(deptNumber);
                    staff.setStaffNumber(s.getStaffNumber());
                    staff.setName(s.getName());
                    staff.setPhone(s.getPhone());
                    staff.setStatus("11");
                    list.add(staff);
                }
            }


        });
        return list;
    }

    /**
     * 获取辅导员列表
     * @return
     */
    @Override
    public List<Staff> getInstructorList() {
        return staffMapper.getInstructorList();
    }

    /**
     * 新增教职工
     * @param staff
     * @return
     */
    @Transactional
    public ResponseResult addStaff(Staff staff) {
        ResponseResult result = new ResponseResult();

        Staff record = findByStaffNumber(staff.getStaffNumber());
        if(null != record){
            result.setCode(HttpStatus.ERROR);
            result.setMsg("新增失败,该教职工已存在");
        }else {

            //新增教职工
            staff.setCreateBy(SecurityUtils.getUsername());
            staff.setCreateDate(DateUtils.getNowDate());
            insertSelective(staff);
            //新增系统用户
            User user = new User();
            user.setPassword(SecurityUtils.encryptPassword(Constants.DEFAULT_PASSWORD));
            user.setAccountName(staff.getName());
            user.setSex(staff.getSex());
            user.setPhone(staff.getPhone());
            user.setUserName(staff.getStaffNumber());
            user.setCreateBy(SecurityUtils.getUsername());
            user.setCreateDate(DateUtils.getNowDate());
            user.setStatus(Constants.ACCOUNT_ENABLE);
            userService.insertSelective(user);
            //创建用户角色
            roleService.addUserRole(user.getId(), Long.valueOf(staff.getRoleId()));

            result.setCode(HttpStatus.SUCCESS);
            result.setMsg("新增教职工成功");
        }
        return result;
    }

    /**
     * 更新教职工
     * @param staff
     * @return
     */
    @Transactional
    public ResponseResult editStaff(Staff staff) {
        ResponseResult result =  new ResponseResult();

        //更改教职工信息
        staff.setUpdateBy(SecurityUtils.getUsername());
        staff.setUpdateDate(DateUtils.getNowDate());
        updateByStaffNumberSelective(staff);

        //更改系统用户角色
        User user = userService.findUser(staff.getStaffNumber());
        roleService.updateUserRole(user.getId(),staff.getRoleId());


        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("教职工信息修改成功");
        return result;
    }

    /**
     * 删除教职工
     * @param staff
     * @return
     */
    @Transactional
    public ResponseResult deleteByStaff(Staff staff) {

        ResponseResult result = new ResponseResult();
        User user = userService.findUser(staff.getStaffNumber());
        //删除教职工信息
        deleteByPrimaryKey(staff.getId());
        //删除角色信息
        roleService.deleteUserRole(user.getId());
        //删除系统用户
        userService.deleteByPrimaryKey(user.getId());
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("删除教职工成功");
        return result;
    }

    /**
     * 查询教职工信息
     * @param staffVo
     * @return
     */
    @Override
    public ResponseResult queryStaffInfo(StaffVo staffVo) {
        ResponseResult result = new ResponseResult();
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("教职工信息查询成功");
        List<StaffVo> staffList = staffMapper.findStaffList(staffVo);
        result.setData(staffList.get(0));
        return result;
    }
}
